package com.hmall.order.interceptor;

import com.hmall.order.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 返回true为放行，false为拦截
     * handler：被调用的处理器对象，本质上是一个方法对象，对反射技术中的Method对象进行了再包装
     * */
    //Handler执行之前执行，一般用于权限控制
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        Object userId = session.getAttribute("authorization");
        if(userId!=null){
            ThreadLocalUtil.setCurrentId((Long) userId);
            return true;
        }
        log.error("没有登录用户信息");
        return false;
    }

    //Handler执行之后渲染视图之前执行，一般用于改变目标视图
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.removeCurrentId();
    }
}
